package com.fling.abcde.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AlertDialog;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.fling.abcde.R;
import com.fling.abcde.base.BaseActivity;
import com.lib.common.bean.BaseResp;
import com.lib.utils.PhotoHelper;
import com.lib.utils.ToastUtils;
import com.lib.utils.XLog;
import com.lib.common.view.CircleImageView;
import com.lib.common.view.ClearEditText;

import java.io.File;
import java.util.HashMap;

import me.jessyan.autosize.AutoSizeConfig;


/**
 * 描述：
 * Created By FengLing at 2020.06.06 006 下午 5:22
 */
public class PersonalDetailActivity extends BaseActivity implements View.OnClickListener {
    private static final int REQUEST_IMAGE_OBTAIN = 0;
    private static final int REQUEST_IMAGE_CROP = 1;

    private TextView mTvNickName;
    private TextView mTvGender;
    private CircleImageView mIvPortrait;

    private AlertDialog mNickNameDialog;
    private AlertDialog mPortraitDialog;
    private ClearEditText mEtNickName;
    private String mNameStr;

    private File mResultFile;
    private File mRawFile;
    private Uri mRawUri;

    private int mCount;
    private String[] mPermissions = {"android.permission.CAMERA", "android.permission.WRITE_EXTERNAL_STORAGE"};

    private PhotoHelper mPhotoHelper;

    public static void start(Context context) {

        Intent intent = new Intent(context, PersonalDetailActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle(getString(R.string.personal_details));
        setContentView(R.layout.activity_personal_details);

        mTvNickName = findViewById(R.id.tv_nickname);
        mTvGender = findViewById(R.id.tv_gender);
        mIvPortrait = findViewById(R.id.iv_portrait);

        findViewById(R.id.ll_portrait).setOnClickListener(this);
        findViewById(R.id.ll_nickname).setOnClickListener(this);
        findViewById(R.id.ll_gender).setOnClickListener(this);

//        mTvNickName.setText(sUser.getNickname());
//        mTvGender.setText("未设置");
//
//        mIvPortrait.setImageUrl(sUser.getPortrait());

        mPhotoHelper = new PhotoHelper();
        mPhotoHelper.setOnPhotoResultListener(new PhotoHelper.OnPhotoResultListener() {
            @Override
            public void onPhotoResult(String url) {
                XLog.i("uri.getPath() = " + url);
            }

            @Override
            public void onCancel() {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_portrait:
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != 0) {
                    if (mCount < 3) {
                        ActivityCompat.requestPermissions(this, mPermissions, 0);
                    } else {
                        Intent in = new Intent();
                        in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        in.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                        in.setData(Uri.fromParts("package", getPackageName(), null));
                        startActivity(in);
                        ToastUtils.makeText(this, "请打开必要的权限,", Toast.LENGTH_SHORT).show();
                    }
                    return;
                }
                modifyPortrait();
                break;
            case R.id.ll_nickname:
                modifyNickName();
                break;
            case R.id.ll_gender:
                AutoSizeConfig instance = AutoSizeConfig.getInstance();
                if (instance.isStop()) {
                    instance.restart();
                } else {
                    instance.stop(this);
                }
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        mCount++;
        if (grantResults[0] == 0) {
            modifyPortrait();
        } else {
            ToastUtils.makeText(this, "请打开必要的权限,", Toast.LENGTH_SHORT).show();
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        mPhotoHelper.onActivityResult(this, requestCode, resultCode, data);
    }

    private void modifyPortrait() {
        if (mPortraitDialog == null) {
            mPortraitDialog = new AlertDialog.Builder(this)
                    .setItems(new String[]{"拍照", "从相册选择"}, (dialog, which) -> {
                        switch (which) {
                            case 0: {
                                mPhotoHelper.takePicture(this);
                            }
                            break;
                            case 1: {
                                mPhotoHelper.selectPicture(this);
                            }
                            break;
                        }
                    }).create();
        }
        mPortraitDialog.show();
    }

    private void modifyNickName() {
        if (mNickNameDialog == null) {
            View view = LayoutInflater.from(this).inflate(R.layout.pop_edit_text, null, false);
            mNickNameDialog = new AlertDialog.Builder(this)
                    .setView(view)
                    .create();
            mEtNickName = view.findViewById(R.id.my_modify_nick_name);
            view.findViewById(R.id.edit_ok).setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    mNameStr = mEtNickName.getText().toString().trim();
                    if (TextUtils.isEmpty(mNameStr)) {
                        mEtNickName.setError("请输入昵称");
                        return;
                    }
                    showLoading();
                    HashMap<String, String> map = new HashMap<>();
                    map.put("userName", mNameStr);
//                    map.put("phoneNum", sUser.getPhone());
//                    mNetManager.doPost(TaskId.UPDATE_USERNAME, NetURL.UPDATE_USERNAME, map, BaseBean.class);
                }
            });
        }
        mNickNameDialog.show();
    }

    @Override
    public void onDataChanged(BaseResp baseResp) {
        super.onDataChanged(baseResp);
//        switch (baseBean.getTaskId()) {
//            case TaskId.UPDATE_USERNAME: {
//                if (baseBean.getRes_code() == 200) {
//                    sUser.setNickname(mNameStr);
//                    mNickNameDialog.dismiss();
//                    mTvNickName.setText(mNameStr);
//                } else {
//                    ToastUtils.makeText(this, baseBean.getRes_msg(), Toast.LENGTH_SHORT).show();
//                }
//            }
//            break;
//            case TaskId.UPDATE_PORTRAIT: {
//                if (baseBean.getRes_code() == 200) {
//                    JSONObject jsonObject = JSON.parseObject(baseBean.getRes_msg());
//                    String url = jsonObject.getString("image");
//                    mIvPortrait.setImageUrl(url);
//                    sUser.setPortrait(url);
//                }
//                hideLoading();
//            }
//            break;
//        }
    }

    @Override
    public void onProgressChanged(Integer progress) {

        showLoading(progress + "%");
    }

    @Override
    protected void onDestroy() {

        if (mNickNameDialog != null && mNickNameDialog.isShowing()) {
            mNickNameDialog.dismiss();
        }
        if (mPortraitDialog != null && mPortraitDialog.isShowing()) {
            mPortraitDialog.dismiss();
        }
        if (mRawFile != null) {
            mRawFile.delete();
        }
        if (mResultFile != null) {
            mResultFile.delete();
        }
        super.onDestroy();
    }
}